import os
import yaml
import mimetypes
from flask import Flask, make_response
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from flask.json.provider import DefaultJSONProvider

from flaskapp.controller.media import media_bp
from flaskapp.controller.token import token_bp
from flaskapp.controller.index import index_bp
from flaskapp.controller.alarm import alarm_bp
from flaskapp.controller.task import task_bp
from flaskapp.controller.user import user_bp
from flaskapp.controller.dictionary import dictionary_bp
from flaskapp.controller.stat import stat_bp

from flaskapp.controller.errors import errors_blueprint
 

# 引入数据库实例
from flaskapp.model.db import db
from bson import ObjectId 
from datetime import datetime,date
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('application/javascript', '.js')

class CustomJSONEncoder(DefaultJSONProvider):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, ObjectId):  
            return str(obj) 
        else:
            return DefaultJSONProvider.default(obj)

def create_app(config_name):
    app = Flask(__name__, static_folder='./static',
                template_folder="./static", static_url_path="")

   
    app.json = CustomJSONEncoder(app)
    app.json.ensure_ascii = False


    
    # 构建配置文件的完整路径
    config_path = os.path.join(os.path.dirname(__file__), '..', 'app.yaml')
    # 读取并加载YAML配置文件
    try:
        with open(config_path, 'r') as f:
            config_info = yaml.safe_load(f)
    except FileNotFoundError:
        print("Configuration file not found!!!")
        return None
    # 获取指定环境的配置，如果没有指定环境，则使用默认的development配置
    flaskr_config = config_info.get(config_name, config_info['development'])
    # 设置 Home 位置
    flaskr_config["SQLALCHEMY_DATABASE_URI"] = flaskr_config["SQLALCHEMY_DATABASE_URI"].replace('${SERVERHOME}', os.environ.get('SERVERHOME'))

    # 配置应用参数
    app.config.from_mapping(flaskr_config)


    # 数据库绑定app
    db.init_app(app)
    app.config["JWT_COOKIE_SECURE"] = False
    app.config["JWT_COOKIE_CSRF_PROTECT"] = False
    app.config["JWT_CSRF_IN_COOKIES"] = False

    app.config['JWT_SECRET_KEY'] = 'abt@20xx'
    app.config["JWT_ACCESS_TOKEN_EXPIRES"] = 3600
    # app.config["JWT_REFRESH_JSON_KEY"] = "token"

    # app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/'
    # app.config['JWT_TOKEN_LOCATION'] = ['cookies']
    app.config["JWT_TOKEN_LOCATION"] = [
        "headers", 'cookies', "json", "query_string"]
    jwt = JWTManager(app)

    CORS(app,supports_credentials=True)

    # 路由
    app.register_blueprint(errors_blueprint)
    
    app.register_blueprint(token_bp)
    app.register_blueprint(index_bp)
    app.register_blueprint(alarm_bp)
    app.register_blueprint(task_bp)
    app.register_blueprint(user_bp)
    app.register_blueprint(dictionary_bp)
    app.register_blueprint(media_bp)
    app.register_blueprint(stat_bp)

    return app
